import router from "./basa/router";
import store from "./config/store";
import { getAuthMenu, getAppToken } from "./config/api/login";
import { getArgs } from "@/basa/utils";
import Cookies from "js-cookie";
import { addUrlPerFix } from "@/basa/utils";
import fakeMenu from "@/basa/utils/fakeMenu";
let menu,
  timer,
  counter = 0;
function parseJson(arr) {
  if (arr.length !== 0) {
    var pp = function(arr) {
      for (var i = 0; i < arr.length; i++) {
        arr[i].meta = {};
        arr[i].menuCode = arr[i].keyword;
        arr[i].meta.isShowSideBar = arr[i].showLeftMenu === 1;
        arr[i].isShowSideBar = arr[i].showLeftMenu === 1;
        if (arr[i].sons && arr[i].sons.length !== 0) {
          arr[i].subMenu = arr[i].sons;
          // console.log(arr[i].name); // 这里可以写菜单的样式结构...
          pp(arr[i].sons);
        } else {
          // console.log(arr[i].name); // 这里可以写菜单的样式结构...
          arr[i].meta.isShowSideBar = arr[i].showLeftMenu === 1;
          arr[i].isShowSideBar = arr[i].showLeftMenu === 1;
        }
      }
    };
    pp(arr);
  }
  menu = arr;
}
router.beforeEach(async (to, from, next) => {
  // 获取AppToken start
  // 开发环境加localhost加临时access_token防止无限重定向登录
  if (window.location.hostname === "localhost") {
    let tempToken = Cookies.get("access_token");
    // Cookies.set("access_token", "temp-token");
    Cookies.set("access_token", tempToken);
  }

  function goLogin() {
    window.location.href =
      addUrlPerFix(process.env.VUE_APP_LOGIN) +
      "?redirectUrl=" +
      encodeURIComponent(window.location.href);
  }
  function getTimer() {
    return setInterval(function() {
      if (!Cookies.get("access_token")) {
        setTimeout(function() {
          goLogin();
        }, 800);
      }
    }, 1000);
  }
  if (Cookies.get("access_token")) {
    store.commit("SET_ACCESS_TOKEN", Cookies.get("access_token"));
    // 缓存有accessToken，开始检测
    timer = timer || getTimer();
    if (to.query.CODE) {
      if (localStorage.appToken === undefined) {
        let res = await getAppToken({
          code: to.query.CODE,
          client_id: to.query.a
        });
        if (res.data.code === "0") {
          // 缓存apptoken
          localStorage.appToken = res.data.message;
          store.commit("SET_APP_TOKEN", localStorage.appToken);
        } else if (res.data.code === "111") {
          // 失效时删除缓存的apptoken和accessToken
          localStorage.removeItem("appToken");
          goLogin();
        } else if (res.data.code === "305" || res.data.code === "307") {
          // 无权限（agentId是错的305—）或没有agentId307
          counter++;
          store.dispatch("setRouter305", {
            isShow: true,
            message: res.data.message
          });
          next({
            replace: true,
            path: `/305?a=${getArgs("a")}`
          });
          return;
        }
      } else {
        store.commit("SET_APP_TOKEN", localStorage.appToken);
      }
    } else {
      if (localStorage.appToken === undefined) {
        // console.log(to.query.a);
        // 走OAuth流程
        if (counter === 0) {
          window.location.href =
            addUrlPerFix(process.env.VUE_APP_LOGIN) +
            "?CLIENT_ID=" +
            to.query.a +
            "&CALLBACK_URL=" +
            encodeURIComponent(window.location.href);
        }
      } else {
        store.commit("SET_APP_TOKEN", localStorage.appToken);
      }
    }
  } else {
    // Cookies里也没有ACCESS_TOKEN,跳登录页
    goLogin();
  }
  // 获取AppToken end
  if (to.path !== "/po") {
    if (store.state.app.routerPower.isShow) {
      next();
      return;
    }
    if (!store.state.app.menu.length) {
      let res = await getAuthMenu({});
      // console.log(res);
      // <-- 应用激活 -->
    //   let appActionRouter = {
    //     showLeftMenu: 0,
    //     code: "100100",
    //     auth: false,
    //     pcode: "",
    //     auths: [],
    //     type: 1,
    //     url: "/appActivation",
    //     viewTemplate: "common-modules/layout/Layout",
    //     sons: [
    //       {
    //         showLeftMenu: 0,
    //         code: "100101",
    //         auth: false,
    //         pcode: "100100",
    //         auths: [],
    //         type: 1,
    //         url: "/appActivation",
    //         viewTemplate: "",
    //         sons: [
    //           {
    //             showLeftMenu: 0,
    //             code: "100102",
    //             auth: false,
    //             pcode: "100101",
    //             sons: [],
    //             auths: [],
    //             type: 2,
    //             url: "/appActivation",
    //             viewTemplate: "appActivation/views/index",
    //             name: "应用中心",
    //             id: 100102,
    //             isGroup: 0,
    //             keyword: "appCenter-appCenterList"
    //           }
    //         ],
    //         name: "应用激活",
    //         id: 104991,
    //         isGroup: 0,
    //         keyword: "appCenter-appCenterList"
    //       }
    //     ],
    //     name: "应用激活",
    //     id: 104990,
    //     isGroup: 0,
    //     keyword: "appCenter"
    //   };

      // res.data.code = "309";
      if (res && (res.data.code === "0" || res.data.code == "309")) {
        // //本地调试想看应用激活模块的
        // res.data.data.root.sons.push(appActionRouter);
        // const arr = res.data.data.root.sons;
        res.data.data.root.sons[0].sons.push(...fakeMenu.contract);
        res.data.data.root.sons[2].sons.push(...fakeMenu.check);
        res.data.data.root.sons[3].sons.push(...fakeMenu.settlement);
        res.data.data.root.sons[5].sons.push(...fakeMenu.management);
        const arr = res.data.data.root.sons;


        //本地调试完，一定要把这个解开，把上面的注释
        // let arr = [];
        // if (res.data.code === "309") {
        //   arr.push(appActionRouter);
        // } else if (res.data.data) {
        //   arr = res.data.data.root.sons;
        // }

        if (arr.length === 0) {
          const contactStr = res.data.data.personName
            ? `，可联系管理员<span style="color: #0089ef">${res.data.data.personName}</span>${res.data.data.mobile}为您授权。`
            : "。";
          store.dispatch("setRouter305", {
            isShow: true,
            message: `您暂无相关功能权限${contactStr}`
          });
          next({
            replace: true,
            path: `/405?a=${getArgs("a")}`
          });
          return;
        }
        arr.forEach(item => {
          item.pid = "1";
          item.id = 1 + "-" + item.code;
          if (item.sons && item.sons.length) {
            item.sons.forEach(item2 => {
              item2.pid = item.id;
              item2.id = item.id + "-" + item2.code;
              if (item2.sons && item2.sons.length) {
                item2.sons.forEach(item3 => {
                  item3.pid = item2.id;
                  item3.id = item2.id + "-" + item3.code;
                  if (item3.sons && item3.sons.length) {
                    item3.sons.forEach(item4 => {
                      item4.pid = item3.id;
                      item4.id = item3.id + "-" + item4.code;
                    });
                  }
                });
              }
            });
          }
        });
        parseJson(arr);
        const routeObj = JSON.parse(JSON.stringify(arr));
        store.dispatch("generateRoutes", routeObj).then(() => {
          router.addRoutes(store.getters.addRouters); // 动态添加可访问路由表
          // 首页跳动态路由第一项
          router.addRoutes([
            {
              path: "",
              redirect: store.getters.addRouters[0].path
            }
          ]); // 动态添加可访问路由表
          if (res.data.code === "309") {
            // router.push("/appActivation");
            // next();
            // next({
            //   replace: true,
            //   path: "/appActivation"
            // });
            router.addRoutes([
              {
                path: "",
                redirect: "/appActivation"
              }
            ]);
          } else if (res.data.code === "0" && to.path === "/appActivation") {
            next({
              path: store.getters.addRouters[0].path,
              replace: true
            }); // hack方法 确保addRoutes已完成 ,set the replace: true so the navigation will not leave a history record
          } else {
            next({
              ...to,
              replace: true
            });
          }
        });
        store.dispatch("setMenu", menu);
      } else if (res && (res.data.code === "305" || res.data.code === "307")) {
        next({
          replace: true,
          path: `/305?a=${getArgs("a")}`
        });
      }
    }

    if (to.name) {
      // 是否隐藏三级菜单
      if (to.meta.isShowSidebar) {
        store.dispatch("openSidebarTemporary");
      } else {
        store.dispatch("closeSidebarTemporary");
      }
    }
    if (to.query.a) {
      next();
    } else {
      let query = to.query;
      query.a = getArgs("a");
      if (!query.a) {
        next();
      } else {
        next({
          path: to.path,
          query: query
        });
      }
    }
  } else {
    next();
    return;
  }
});
